package cn.tedu.forum.passport.security;

import cn.tedu.forum.passport.mapper.LoginMapper;
import cn.tedu.forum.passport.pojo.vo.LoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private LoginMapper loginMapper;

    @Override
    public UserDetails loadUserByUsername(String phoneNumber) throws UsernameNotFoundException {
        log.debug("根据联系电话（{}）查找用户信息……", phoneNumber);
        LoginVO loginVO = loginMapper.getLoginInfoByPhoneNumber(phoneNumber);
        log.debug("查找到的用户信息为：{}", loginVO);
        if (loginVO == null) {
            log.error("登录失败，用户名不存在！");
            throw new BadCredentialsException("--- 用户名不存在 ---");
        }
        // 检查是否启用
        if (loginVO.getEnable() != 1) {
            throw new BadCredentialsException("登录失败，用户账号已经被禁用！");
        }
        UserDetails userDetails = User.builder()
                .username(loginVO.getPhoneNumber())
                .password(loginVO.getPassword())
                .accountExpired(false)
                .accountLocked(false)
                .disabled(false)
                .credentialsExpired(false)
                .authorities(loginVO.getPermissions().toArray(new String[]{}))
                .build();
        log.debug("将向Spring Security返回尝试登录的用户信息：{}", userDetails);
        // 返回
        return userDetails;
    }
}
